package com.bestcem.xm.deliver.controller;

import cn.hutool.core.lang.ObjectId;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.servlet.ServletUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bestcem.xm.common.core.annotation.XmGet;
import com.bestcem.xm.common.core.constant.ReqErrorCodeConstants;
import com.bestcem.xm.common.core.domain.web.XmResultJson;
import com.bestcem.xm.component.security.annotation.AuthIgnore;
import com.bestcem.xm.deliver.controller.v2.param.GetCustomlinkPageParam;
import com.bestcem.xm.deliver.controller.v2.param.GetDeliverextparamsPageParam;
import com.bestcem.xm.deliver.entity.DeliverCustomLink;
import com.bestcem.xm.deliver.entity.DeliverDeliver;
import com.bestcem.xm.deliver.entity.DeliverDeliverExtParams;
import com.bestcem.xm.deliver.service.DeliverCustomLinkService;
import com.bestcem.xm.deliver.service.DeliverDeliverExtParamsService;
import com.bestcem.xm.deliver.util.PageUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.Objects;


@Slf4j
@Api(tags = "问卷投放-自定义链接")
@RestController
@RequiredArgsConstructor
@RequestMapping("/deliver")
public class DeliverCustomlinkController {
    private @NonNull DeliverCustomLinkService deliverCustomLinkService;
    private @NonNull DeliverDeliverExtParamsService deliverDeliverExtParamsService;

    @ApiOperation(value = "自定义链接列表")
    @GetMapping(value = {"/customlinks/{id:[a-fA-F0-9]{24}}", "/customlinks/"})
    public XmResultJson<Object> getCustomlinks(@ApiIgnore Page<DeliverCustomLink> page,
                                               @XmGet GetCustomlinkPageParam param,
                                               @PathVariable(value = "id", required = false) String id,
                                               HttpServletRequest request) {
        if (Objects.nonNull(id)) {
            return XmResultJson.success(deliverCustomLinkService.getById(id));
        }
        if (!PageUtil.isPageQuery(request)) {
            return XmResultJson.success(deliverCustomLinkService.getCustomlinksList(param));
        }
        return XmResultJson.success(deliverCustomLinkService.getCustomlinks(page, param));
    }

    @ApiOperation(value = "自定义链接列表-外部参数")
    @GetMapping(value = {"/deliverextparamss/{id:[a-fA-F0-9]{24}}", "/deliverextparamss/"})
    public XmResultJson<Object> getDeliverextparamss(@ApiIgnore Page<DeliverDeliverExtParams> page,
                                                     @XmGet GetDeliverextparamsPageParam param,
                                                     @PathVariable(value = "id", required = false) String id,
                                                     HttpServletRequest request) {
        //当url指定id时，直接查询该id的DeliverExtparams，忽略其他筛选参数
        //当url没有指定id时，返回分页查询结果，参数在query中
        if (ObjectId.isValid(id)) {
            return XmResultJson.success(deliverDeliverExtParamsService.getOneDeliverextparams(id));
        } else {
            if ("".equals(param.getDeliverId()) || ObjectUtil.isNull(param.getDeliverId())) {
                return XmResultJson.fail(-1, "缺少deliver_id");
            }
            if (!PageUtil.isPageQuery(request)) {
                return XmResultJson.success(deliverDeliverExtParamsService.getDeliverextparamsList(param));
            }
            return XmResultJson.success(deliverDeliverExtParamsService.getCustomlinks(page, param));
        }

    }

    @ApiOperation(value = "自定义链接下载")
    @GetMapping("/customlinks/download")
    public XmResultJson<Map<String, String>> getCustomlinksDownload(@XmGet GetCustomlinkPageParam param) {
        if ("".equals(param.getDeliverId()) || ObjectUtil.isNull(param.getDeliverId())) {
            return XmResultJson.fail(-1, "缺少deliver_id");
        }
        return XmResultJson.success(deliverCustomLinkService.getCustomlinksDownload(param.getDeliverId()));
    }

    @ApiOperation(value = "自定义链接拼接参数-模板")
    @GetMapping("/downloads/external_parameter_template")
    public XmResultJson<Map<String, String>> getExternalParameterTemplate(@XmGet GetCustomlinkPageParam param) {
        if ("".equals(param.getDeliverId()) || ObjectUtil.isNull(param.getDeliverId())) {
            return XmResultJson.fail(-1, "缺少deliver_id");
        }
        return XmResultJson.success(deliverCustomLinkService.getExternalParameterTemplate(param.getDeliverId()));
    }

    @ApiOperation(value = "自定义链接投放列表查询")
    @GetMapping(value = {"/all/customdeliver/{id}", "/all/customdeliver/"})
    public XmResultJson<Object> getAllCustomdeliver(@ApiIgnore Page<DeliverDeliver> page,
                                                    @XmGet GetCustomlinkPageParam param,
                                                    @PathVariable(value = "id", required = false) String id) {
        return XmResultJson.success(deliverCustomLinkService.getAllCustomdeliver(page, param, id));
    }

    @ApiOperation(value = "自定义链接保存")
    @PostMapping("/customlink/")
    public XmResultJson<Map<String, String>> saveCustomlink(@RequestBody JSONObject param, HttpServletRequest request) {
        String baseUrl = request.getScheme() + "://" + request.getServerName();
        return XmResultJson.success(deliverCustomLinkService.saveCustomlink(param, baseUrl));
    }

    @ApiOperation(value = "自定义链接编辑")
    @PutMapping("/customlink/")
    public XmResultJson<Map<String, String>> putCustomlink(@RequestBody JSONObject param, HttpServletRequest request) {
        String baseUrl = request.getScheme() + "://" + request.getServerName();
        return XmResultJson.success(deliverCustomLinkService.putCustomlink(param, baseUrl));
    }

    @ApiOperation(value = "自定义链接拼接-上传")
    @PostMapping("/upload/ext_param_template/")
    public XmResultJson<Map<String, String>> extParamTemplateImport(@RequestParam(value = "file") MultipartFile file,
                                                                    @RequestParam(value = "group_id") String groupId,
                                                                    @RequestParam(value = "deliver_id") String deliverId) {
        if (Objects.isNull(file)) {
            return XmResultJson.fail(ReqErrorCodeConstants.PARAM_LOST, ":file is lost");
        }
        return XmResultJson.success(deliverCustomLinkService.extParamTemplateImport(file, groupId, deliverId));
    }

    @ApiOperation(value = "自定义链接")
    @GetMapping("/c_l_deliver")
    @AuthIgnore
    public void getCLDeliver(HttpServletRequest request, HttpServletResponse response) {
        deliverCustomLinkService.getCLDeliver(request, response);
    }

    @ApiOperation(value = "自定义链接")
    @PostMapping("/c_l_deliver")
    @AuthIgnore
    public XmResultJson<?> postCLDeliver(@RequestBody JSONObject param, HttpServletRequest request) {
        Map<String, String> urlParamMap = ServletUtil.getParamMap(request);
        return XmResultJson.success(deliverCustomLinkService.postCLDeliver(urlParamMap, param, request).getString("url"));
    }

}
